# -*- coding: utf-8 -*-
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys

from google.appengine.api import users

from google.appengine.ext import db
from google.appengine.ext.db import djangoforms

import django
from django import http
from django.http import HttpResponseRedirect, HttpResponse
from django import shortcuts
import pyxn.djangoxn as xn
from django.utils import simplejson
import logging

sys.path.append(os.path.join(os.path.dirname(__file__), "lib/feedparser"))
import feedparser

# Feeds: url,userid,dirname,title,created
class Feeds(db.Model):
  userId = db.StringProperty()
  dirName = db.StringProperty()
  feedTitle = db.StringProperty()
  url = db.URLProperty(required=True)
  created = db.DateTimeProperty(auto_now_add=True)

class FeedForm(djangoforms.ModelForm):
  class Meta:
    model = Feeds
    exclude = ['userId', 'created']

def respond(request, user, template, params=None):
  """Helper to render a response, passing standard stuff to the response.

  Args:
    request: The request object.
    user: The User object representing the current user; or None if nobody
      is logged in.
    template: The template name; '.html' is appended automatically.
    params: A dict giving the template parameters; modified in-place.

  Returns:
    Whatever render_to_response(template, params) returns.

  Raises:
    Whatever render_to_response(template, params) raises.
  """
  if params is None:
    params = {}
  if user:
    params['user'] = user
    params['sign_out'] = users.create_logout_url('/')
    params['is_admin'] = (users.is_current_user_admin() and
                          'Dev' in os.getenv('SERVER_SOFTWARE'))
  else:
    params['sign_in'] = users.create_login_url(request.path)
  if not template.endswith('.html'):
    template += '.html'
  return shortcuts.render_to_response(template, params)

@xn.require_add()
def index(request):
  """Request / -- show all gifts."""
  xn = request.xiaonei
    #make api calls now
  info = xn.users.getInfo(uids=[xn.uid,], fields=["name","sex","hometown_location"])
  user = users.get_current_user()

  feeds = db.GqlQuery('SELECT * FROM Feeds ORDER BY created DESC')

  return respond(request, user, 'list', {'user': info, 'feeds':feeds})

def feed_list(request):
  feeds = ["http://hi.baidu.com/mabo/rss", "http://hi.baidu.com/leeight/rss"]
  user = users.get_current_user()
  return respond(request, user, 'feed_list', { 'feeds' : feeds })

def read_feed(request, feed):
  user = users.get_current_user()
  document = feedparser.parse(feed)
  return respond(request, user, 'read_feed', { 'document' : document } )

def add(request):
  logging.getLogger().setLevel(logging.DEBUG)
  logging.debug('callback.add.request = %s', request)
  return HttpResponse("callback.add")

def delete(request):
  logging.getLogger().setLevel(logging.DEBUG)
  logging.debug('callback.delete.request = %s', request)
  return HttpResponse("callback.delete")

def edit(request, feed_id):
  """Create or edit a gift.  GET shows a blank form, POST processes it."""
  user = users.get_current_user()
#  if user is None:
 #   return http.HttpResponseForbidden('You must be signed in to add or edit a gift')

  feed = None
  if feed_id:
    feed = Feeds.get(db.Key.from_path(Feeds.kind(), int(feed_id)))
    if feed is None:
      return http.HttpResponseNotFound('No gift exists with that key (%r)' %
                                       feed_id)

  form = FeedForm(data=request.POST or None, instance=feed)

  if not request.POST:
    return respond(request, user, 'list', {'form': form, 'feed': feed})
  
  errors = form.errors

  if not errors:
    try:
      feed = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
    return respond(request, user, 'list', {'errors': errors, 'feed': feed})

  if not feed.userId:
    feed.userId = "252565488"
  feed.put()

  return http.HttpResponseRedirect('/')
#feed.userId = "252565488"
 # feed.put()
  #return http.HttpResponseRedirect('/')

def new(request):
  """Create a gift.  GET shows a blank form, POST processes it."""
  return edit(request, None)
